<?php


namespace backend\controllers;

use common\helps\tools;
use Yii;
use backend\models\Warehouse;
use yii\web\AdminController;

class PrebillController extends AdminController
{

    public $layout = false;
    //业务关键字
    public $service = 'bill';

    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionGetPrebill()
    {
        $data = Yii::$app->request->post();
        $preBillNo = $data['preBillNo'];

        $preBillSql = "SELECT * FROM j_bill_pre WHERE preBillNo = '{$preBillNo}'";
        $preBill = Yii::$app->db->createCommand($preBillSql)->queryOne();

        $preBillDtlSql = "SELECT j_bill_dtl_pre.*,j_materiel.materielCode,j_materiel.materielName FROM j_bill_dtl_pre JOIN j_materiel ON j_bill_dtl_pre.materielId = j_materiel.id WHERE j_bill_dtl_pre.preBillNo ='{$preBillNo}'";
        $preBillDtlList = Yii::$app->db->createCommand($preBillDtlSql)->queryAll();

        $preBill['details'] = $preBillDtlList;

        $this->retJson('操作成功', 200, $preBill);
    }

    public function actionPayPrebill(){

        $data = Yii::$app->request->post();
        $preBillNo = $data['preBillNo'];
        $payBillNo = $data['payBillNo'];

        $sql = "UPDATE j_bill_pre SET billStatus = 2,orderDesc='{$payBillNo}' WHERE preBillNo = '{$preBillNo}' AND billStatus != 2";
        $result = Yii::$app->db->createCommand($sql)->execute();
        if ($result) {
            $preBillSql = "SELECT * FROM j_bill_pre WHERE preBillNo = '{$preBillNo}'";
            $preBill = Yii::$app->db->createCommand($preBillSql)->queryOne();

            $preBillDtlSql = "SELECT * FROM j_bill_dtl_pre WHERE preBillNo = '{$preBillNo}'";
            $preBillDtlList = Yii::$app->db->createCommand($preBillDtlSql)->queryAll();

            $newTime = date('Y-m-d H:i:s');
            $tempGroup = [];
            foreach ($preBillDtlList as $dtl) {
                $tempGroup[$dtl['warehouseId']][] = $dtl;
            }

            $billArr = [];
            $billDtl = [];
            $billNos = [];
            foreach ($tempGroup as $warehouseId => $dtls) {


                $billNo = tools::getBillNo(date('Ymd'), 'seq_bill_no', 6);
                $ck_bil_no = Yii::$app->db->createCommand("SELECT count(0) cnt FROM j_bill WHERE billNo='" . $billNo . "'")->queryOne();
                if ($ck_bil_no['cnt']) {
                    $this->retJson('网络异常，请重试', 500);
                }

                $subQty = 0;
                $subPrice = 0;
                foreach ($dtls as $dtl) { //订单明细
                    $billDtl[] = array(
                        'creator' => $preBill['userId'],
                        'createTime' => $newTime,
                        'billNo' => $billNo,
                        'materielId' => $dtl['materielId'],
                        'qty' => $dtl['qty'],
                        'deliverQty' => 0,
                        'deliverAmount' => 0,
                    );
                    $subQty += $dtl['qty'];
                    $subPrice += ($dtl['qty'] * $dtl['referPrice']);
                }

                $billArr[] = array(
                    'billNo' => $billNo,
                    'creator' => $preBill['userId'],
                    'createTime' => $newTime,
                    'orderType' => 1, //1前台 2后台
                    'billStatus' => 0,
                    'userId' => $preBill['userId'],
                    'warehouseId' => $warehouseId,
                    'sendDate' => date("Y-m-d", strtotime("+1 day")),
                    'shopId' => $preBill['shopId'],
                    'address' => $preBill['address'],
                    'totalQty' => $subQty,
                    'totalAmount' => $subPrice,
                );

                $billNos[] = $billNo;

            }
            $transaction = Yii::$app->db->beginTransaction();
            try {

                $billNoValue = implode(",", $billNos);
                $billNosql = "UPDATE j_bill_pre SET billNo = '{$billNoValue}' WHERE preBillNo = '{$preBillNo}'";
                $result = Yii::$app->db->createCommand($billNosql)->execute();

                //添加订单
                foreach ($billArr as $bill) {
                    Yii::$app->db->createCommand()->insert('j_bill', $bill)->execute();
                }
                //添加订单明细
                $delSql = '';
                foreach ($billDtl as $addDtl) {
                    Yii::$app->db->createCommand()->insert('j_bill_dtl', $addDtl)->execute();
                    $delSql .= "DELETE FROM j_cart WHERE materielId='{$addDtl['materielId']}' AND userId='{$preBill['userId']}';";
                }
                Yii::$app->db->createCommand($delSql)->execute();

                $transaction->commit();
                $this->retJson('操作成功', 200);
            } catch (\Exception $e) {
                $transaction->rollBack();
                Yii::error("异常:" . $e->getMessage() . $e->getLine());
                $this->retJson('数据异常,请重试', 500);
            }
        }

        $this->retJson('数据异常,请重试', 500);
    }



}